package cn.flying.cloud.core.auth.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSON;

import cn.flying.cloud.base.common.enums.RtCodeEnum;
import cn.flying.cloud.base.common.vo.Rt;

/**
 * @description: 未登录访问（匿名用户访问）无权限资源时的异常处理器
 * @author: admin
 * @date: 2023年05月25日 19:29
 * @version: 1.0
 */
@Component
public class CustomUnauthorizedEntryPointHandler implements AuthenticationEntryPoint {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * @param request   that resulted in an <code>AuthenticationException</code>
     * @param response  so that the user agent can begin authentication
     * @param exception that caused the invocation
     */
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
        logger.error("认证异常，匿名用户访问未授权资源", exception);

        //判断请求类型，根据不同的类型返回
        String xmlHttpRequest = "XMLHttpRequest";
        String requestedWith = request.getHeader("x-requested-with");
        if (requestedWith != null && requestedWith.equalsIgnoreCase(xmlHttpRequest)) {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write(JSON.toJSONString(Rt.error(RtCodeEnum.R10014)));
            out.flush();
            out.close();
        } else {
            //访问页面的直接跳转到登录页面
            new DefaultRedirectStrategy().sendRedirect(request, response, "/auth/login/page");
            //这里采用转发的方式，因为重定向后浏览器的地址变了
//            request.getRequestDispatcher("/auth/login/page").forward(request, response);
        }
    }
}
